package com.guaju.yueshangLife.fragment.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.activity.MainActivity;
import com.guaju.yueshangLife.adapter.OrderListAdapter;
import com.guaju.yueshangLife.bean.CancleOrderBean;
import com.guaju.yueshangLife.bean.MeOrder;
import com.guaju.yueshangLife.bean.MineOrder;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.utils.CommonUtils;
import com.guaju.yueshangLife.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UncommentFragment extends OrderListFragment {
    private static final String TAG = "UncommentFragment";
    public static final String TYPE = "type";
    private String status;
    private int page = 1;
    private int limit = 10;
    private boolean isRefresh = false;
    private LinearLayoutManager layoutManager;
    private ArrayList<MineOrder.DataBean> orderList = new ArrayList<>();
    private OrderListAdapter orderListAdapter;
    private static OrderListFragment orderListFragment;

    @Override
    public int setContent() {
        return R.layout.fragment_order_list;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        EventBus.getDefault().register(this);
        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }
            return view;
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListener();

        Bundle arguments = getArguments();
        if (arguments != null) {
            status = arguments.getString(TYPE);
            hideEmpty();
            layoutManager = new LinearLayoutManager(getActivity()) {
                @Override
                public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                    return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                }

            };
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            bindingView.recyclerview.setLayoutManager(layoutManager);
            orderListAdapter = new OrderListAdapter(getActivity(), orderList);
            bindingView.recyclerview.setAdapter(orderListAdapter);

        } else {
            showEmpty();
        }
        scrollRecycleView();
        showContentView();
        addProgressPic();
    }

    public void realLoadData() {
        page = 1;
        ApiEntity.meOrderCall(status, page, limit, new Callback<MineOrder>() {
            @Override
            public void onResponse(Call<MineOrder> call, Response<MineOrder> response) {
                if (bindingView.srl.isRefreshing()) bindingView.srl.setRefreshing(false);
                if (response.isSuccessful()) {
                    MineOrder body = response.body();
                    if (body == null || body.getData() == null || body.getData().isEmpty()) {
                        showEmpty();
                    } else {
                        hideEmpty();
                        List<MineOrder.DataBean> data = body.getData();
                        orderList.clear();
                        orderList.addAll(data);
                        orderListAdapter.notifyDataSetChanged();
                        if (data.size() < limit) {
                            orderListAdapter.updateLoadStatus(orderListAdapter.LOAD_END);
                        }
                    }
                    if (isRefresh) {
                        isRefresh = false;
                        bindingView.srl.setRefreshing(false);
                    }

                } else {
                    showEmpty();
                    if (isRefresh) {
                        isRefresh = false;
                        bindingView.srl.setRefreshing(false);
                    }
                }
            }

            @Override
            public void onFailure(Call<MineOrder> call, Throwable t) {
                if (bindingView.srl.isRefreshing()) bindingView.srl.setRefreshing(false);
                showEmpty();
                if (isRefresh) {
                    isRefresh = false;
                    bindingView.srl.setRefreshing(false);
                }
            }
        });
    }

    private void hideEmpty() {
        if (news_loading != null) {
            news_loading.setVisibility(View.GONE);
        }
        bindingView.orderEmpty.getRoot().setVisibility(View.GONE);
        bindingView.llList.setVisibility(View.VISIBLE);
    }

    private void showEmpty() {
        if (news_loading != null) {
            news_loading.setVisibility(View.GONE);
        }
        bindingView.orderEmpty.getRoot().setVisibility(View.VISIBLE);
        bindingView.orderEmpty.tvOrderEmpty.setText("暂无订单信息");
        bindingView.llList.setVisibility(View.GONE);
    }

    private void setListener() {

        bindingView.srl.setColorSchemeColors(CommonUtils.getColor(R.color.colorTheme));
        bindingView.srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                bindingView.srl.post(new Runnable() {
                    @Override
                    public void run() {
                        page = 1;
                        isRefresh = true;
                        realLoadData();

                    }
                });

            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        realLoadData();
    }

    @Override
    public void loadData() {
//        realLoadData();

    }

    //计算recyclerview滑动，展示下拉刷新，上拉加载
    public void scrollRecycleView() {
        bindingView.recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    lastVisibleItem = layoutManager.findLastVisibleItemPosition();

                    /**StaggeredGridLayoutManager*/
//                    int[] into = new int[(layoutManager).getSpanCount()];
//                    lastVisibleItem = findMax(layoutManager.findLastVisibleItemPositions(into));

                    if (orderListAdapter == null) {
                        return;
                    }
                    if (layoutManager.getItemCount() == 0) {
                        orderListAdapter.updateLoadStatus(orderListAdapter.LOAD_END);
                        return;

                    }
                    if (lastVisibleItem + 1 == layoutManager.getItemCount()
                            && orderListAdapter.getLoadStatus() != orderListAdapter.LOAD_MORE) {
//                        mBookAdapter.updateLoadStatus(BookAdapter.LOAD_PULL_TO);
                        // isLoadMore = true;
                        orderListAdapter.updateLoadStatus(orderListAdapter.LOAD_MORE);
                        page++;


                        if (!TextUtils.isEmpty(status)) {
                            ApiEntity.meOrderCall(status, page, limit, new Callback<MineOrder>() {
                                @Override
                                public void onResponse(Call<MineOrder> call, Response<MineOrder> response) {
                                    if (response.isSuccessful()) {
                                        MineOrder goodsListTotal = response.body();

                                        if (goodsListTotal != null) {
                                            List<MineOrder.DataBean> data = goodsListTotal.getData();
                                            //说明刷新到了最底部
                                            if (data == null || data.isEmpty()) {
                                                orderListAdapter.updateLoadStatus(orderListAdapter.LOAD_END);
                                            } else {
                                                for (MineOrder.DataBean bean : data) {
                                                    orderList.add(bean);
                                                }
                                                loadCustomData(data);
                                            }
                                        }

                                    }
                                }

                                @Override
                                public void onFailure(Call<MineOrder> call, Throwable t) {

                                }
                            });
                        }
                    }
                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                /**StaggeredGridLayoutManager*/
//                int[] into = new int[(layoutManager).getSpanCount()];
//                lastVisibleItem = findMax(layoutManager.findLastVisibleItemPositions(into));
            }
        });
    }

    private void loadCustomData(List data) {
        if (orderListAdapter == null) {
            orderListAdapter = new OrderListAdapter(getActivity(), orderList);
            bindingView.recyclerview.setAdapter(orderListAdapter);
        } else {
            if (data.size() < limit) {
                orderListAdapter.updateLoadStatus(orderListAdapter.LOAD_END);
            } else {
                orderListAdapter.updateLoadStatus(orderListAdapter.LOAD_PULL_TO);

            }
        }
        if (bindingView.srl.isRefreshing()) {
            bindingView.srl.setRefreshing(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCancleOrderReceived(CancleOrderBean bean) {
        if (bean == null) {
            ToastUtil.show("内部异常,请稍后重试");
        } else {
            int code = bean.getCode();
            if (200 == code) {
                ToastUtil.show("已取消订单");
                realLoadData();
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
